package cn.com.elite;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;

public class Mailrun implements Runnable{
	private static final Log log=LogFactory.getLog(Mailrun.class);
	public static String address=""; //用于发�?�EMAIL的发送�?�地�? 
	public static String username=""; //发�?��?�的用户�? 
	public static String password=""; //发�?��?�的密码 
	public static String SMTPHost=""; //IP
	public static String mail_sql=""; //查询MAIL的SQL语句
	public static String eml_path="";  //存放临时EML文件的地�?
	public static String f_path="";   //存放临时附件的地�?
	public static String dotime="";   //运行时间
	public static String systemcode="";
	public static cn.com.elite.MailBean mailbean;
	public static String http="";
	private static String FTPMOD="";
	private static String FTPWAV="";
	
	public static String getHttp() {
		return http;
	}
	public static void setHttp(String http) {
		Mailrun.http = http;
	}
	public static String getAddress() {
		return address;
	}
	public static void setAddress(String address) {
		Mailrun.address = address;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		Mailrun.username = username;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) {
		Mailrun.password = password;
	}
	public static String getSMTPHost() {
		return SMTPHost;
	}
	public static void setSMTPHost(String host) {
		SMTPHost = host;
	}
	public static String getMail_sql() {
		return mail_sql;
	}
	public static void setMail_sql(String mail_sql) {
		Mailrun.mail_sql = mail_sql;
	}
	public static String getEml_path() {
		return eml_path;
	}
	public static void setEml_path(String eml_path) {
		Mailrun.eml_path = eml_path;
	}
	public static String getF_path() {
		return f_path;
	}
	public static void setF_path(String f_path) {
		Mailrun.f_path = f_path;
	}
	public static String getDotime() {
		return dotime;
	}
	public static void setDotime(String dotime) {
		Mailrun.dotime = dotime;
	}
	public static String getSystemcode() {
		return systemcode;
	}
	public static void setSystemcode(String systemcode) {
		Mailrun.systemcode = systemcode;
	}
	public static cn.com.elite.MailBean getMailbean() {
		return mailbean;
	}
	public static void setMailbean(cn.com.elite.MailBean mailbean) {
		Mailrun.mailbean = mailbean;
	}
	public static void main(String[] args){
		System.out.println("1");
		ReadEmail readmail=new ReadEmail();
		System.out.println("2");
	}
	public static String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}	
	public void run(){
		try{
			FTPMOD=getFTPMOD();
			log.info("FTPMOD:"+FTPMOD);
			if(FTPMOD.equals("2")){
				FTPWAV=getFTPOUT();
			}else if(FTPMOD.equals("3")){
				FTPWAV=getFTPOUT();
			}else{
				log.error("FTPMOD:"+FTPMOD);
			}
		}catch(Exception e){
			log.info("FTPMOD失败:"+getERRO(e));
		}
		log.info("FTPWAV:"+FTPWAV);
		while(true){
			try {
				log.info("-----1-----");
				dorun();
				log.info("-----2-----");
			} catch (Exception e) {
				log.info("dorun()失败:"+getERRO(e));
			}
			try{
				Thread.sleep(Integer.parseInt(dotime)*1000);
			}catch(Exception e){
				log.info("Thread.sleep失败:"+getERRO(e));
			}	
		}
	}
	public void dorun() throws Exception{
		String temp_address="";
		List list=getmail();
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				boolean aa=false;
				String documentout_guid="";
				FTPClient ftp=null;
				try{
					Map map=(Map)list.get(i);
					String path=(String)map.get("documentpath");
					documentout_guid=(String)map.get("documentout_guid");
					log.info("documentpath:"+path);
					String flag="";
					if(FTPMOD.equals("2")){
						String[] param=FTPWAV.split(",");
						if(param.length==3){
							ftp=GetFtp(param[0],Integer.parseInt(param[1]),param[2],"");
						}else if(param.length>3){
							ftp=GetFtp(param[0],Integer.parseInt(param[1]),param[2],param[3]);
						}else{
							log.error("FTPWAV:"+FTPWAV);
						}
						flag=downloadfile(path,eml_path,ftp);
					}else if(FTPMOD.equals("3")){
						flag=downloadfile1(path,eml_path);
					}else{
						log.error("FTPMOD:"+FTPMOD);
					}	
					log.info("flag:"+flag);
					temp_address=flag;
					if(!flag.equals("fail")){
						InputStream fis = new FileInputStream(flag);
						Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
					    MimeMessage msg = new MimeMessage(mailSession,fis);
						ReadEmail readmail=new ReadEmail(msg);
						Map map1=readmail.readmail(msg,f_path);
						log.info("map1:"+map1);
						log.info("开始删除临时文件:"+temp_address);
						MailSend mailsend=new MailSend();
						aa=mailsend.send(address,SMTPHost,username,password,map1);
						log.info("aa:"+aa);
					}else{
						log.error("downloadfile失败");
					}
				}catch(Exception e){
					if(ftp!=null){
						ftp.logout();
						ftp.disconnect();
					}
					log.info("发送过程失败:"+getERRO(e));
				}
				try{
					String sql="";
					if(aa==true){
						sql="update  documentout set status=1,finishdatetime=now(),modifieddate=now(),TrialCount=TrialCount+1 where documentout_guid='"+documentout_guid+"'";
					}else{
						sql=" update DocumentOut set FailCode=0,FailDescription='fail',Status=5,TrialCount=TrialCount+1,LastTryDateTime=now(),FinishDateTime=now(),ModifiedDate=now() where DocumentOut_GUID='"+documentout_guid+"'";
					}
					int a=mailbean.update(sql);
					log.info("更新documentout表记录:"+sql+":"+a);
					File file=new File(temp_address); 
					boolean delete_result=file.delete();
					log.info("开始删除临时文件结果:"+delete_result);
				}catch(Exception e){
					log.info("发送过程失败SQL:"+getERRO(e));
				}
			}
		}
		
	}
	private List getmail() throws Exception{
		List list=null;
		list=mailbean.chaxun(mail_sql);
		return list;
	}
	private String getFTPMOD() throws Exception{
		String sql="select PARAMETERVALUE from sysc_parameter where PARAMETER_ID='FTPMOD'";
		log.info("查询FTPMOD:"+sql);
		String FTPMOD="";
		FTPMOD=mailbean.chaxun1(sql);
		return FTPMOD;
	}
	
	private FTPClient GetFtp(String host,int port,String username1,String password1)throws Exception{
		FTPClient ftp;
		ftp=new FTPClient(); 
		ftp.connect(host,port);
		log.info("host:"+host);
		log.info("port:"+port);
		ftp.setControlEncoding("GBK");
		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
		conf.setServerLanguageCode("zh");
		log.info("username:"+username1);
		log.info("password:"+password1);
		ftp.login(username1,password1);
		return ftp;
	}
	private void FTPCLOSE(FTPClient ftp)throws Exception{
		ftp.logout();
		ftp.disconnect();
	}
	private String downloadfile(String path,String eml_path,FTPClient ftp)throws Exception{
		String newpath=eml_path+"/"+getfilename(path);
		boolean flag=false;
		log.info("下载文件的新路径:"+newpath);
		File newfile=new File(newpath); 
		if(newfile.exists()){
			boolean a=newfile.delete();
			log.info("删除旧文件是否成功:"+a);
			flag=tofile(newfile,ftp,path);
			log.info("tofile是否成功:"+flag);
		}else{
			flag=tofile(newfile,ftp,path);
			log.info("tofile是否成功:"+flag);
		}		
		if(flag==true){
			return newpath;
		}else{
			return "fail";
		}
	}
	
	private String downloadfile1(String path,String eml_path)throws Exception{
		String newpath=eml_path+"/"+getfilename(path);
		boolean flag=false;
		log.info("下载文件的新路径:"+newpath);
		File newfile=new File(newpath); 
		if(newfile.exists()){
			boolean a=newfile.delete();
			log.info("删除旧文件是否成功:"+a);
			flag=tofile1(newfile,path);
			log.info("tofile1是否成功:"+flag);
		}else{
			flag=tofile1(newfile,path);
			log.info("tofile1是否成功:"+flag);
		}		
		if(flag==true){
			return newpath;
		}else{
			return "fail";
		}
	}
	private String getfilename(String path)throws Exception{
		String a=path.substring(path.lastIndexOf("/")+1,path.length());
		return a;
	}
	private boolean tofile(File newfile,FTPClient ftp,String path)throws Exception{
		FileOutputStream fos=null;
		fos=new FileOutputStream(newfile);
		boolean flag=false;
		log.info("path:"+path);
		String path1=path.substring(1, path.length());
		log.info("path1:"+path1);
		flag = ftp.retrieveFile(path1,fos);
		log.info("下载EML文件是否成功:"+flag);
		return flag;
	}
	private boolean tofile1(File newfile,String path)throws Exception{
		int bytesum=0;  
	    int byteread=0; 
	    log.info("http:"+http);
	    log.info("URL:"+http);
		URL url=new URL(http+path);
		URLConnection conn=url.openConnection();
		InputStream inStream=conn.getInputStream();
		FileOutputStream fs=new FileOutputStream(newfile); 
		byte[] buffer=new byte[1204]; 
		while((byteread=inStream.read(buffer))!=-1){
			bytesum+=byteread;  
            fs.write(buffer,0,byteread); 
		}
		return true; 
	}
	private String getFTPOUT()throws Exception{
		String sql="select PARAMETERVALUE from sysc_parameter where PARAMETER_ID='FTPOUT'";
		log.info("查询FTPOUT:"+sql);
		String FTPOUT=mailbean.chaxun1(sql);
		return FTPOUT;
	}
	

}
